/*
 * ManejadorPermiso.java
 */
package servlets;

import beans.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

import dbUtil.*;
import iteradores.*;

/**
 *
 * @author Administrador
 */
public class ManejadorPermisoporModulo extends HttpServlet {

    private String nombreModulo = "permisoxmodulo";
    private IteradorUsuario usuarioActual;

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("windows-1252");
        PrintWriter out = response.getWriter();
        String url = null;

        try {
            //Datos del modulo actual de la sesion, si esto es nulo significa
            //que aun no hizo login
            usuarioActual = (IteradorUsuario) request.getSession().getAttribute("usuarioActual");
            if (usuarioActual == null) {
                url = "login.jsp"; //Volver a loguearse

            } else {
                // Obtiene la conexión a la base de datos de la sesión
                Connection con = (Connection) request.getSession().getAttribute("ConexionBd");
                //Obtiene la operación a realizar 
                String str_op = request.getParameter("op");

                if (str_op != null) {
                    //Objeto que averigua si el modulo tiene permisoxmodulo para acceder al servlet.
                    PgAbm testPermiso = new PgAbm();
                    testPermiso.setCon(con);

                    usuarioActual.getReset();
                    usuarioActual.getNext();
                    if (testPermiso.tienePermiso(nombreModulo,
                            usuarioActual.getNombreusuario(),
                            str_op.substring(0, 6))) {
                        url = "permisoxmodulo.jsp?modo=ASIGNA";

                        if (str_op.equals("SELECT")) {
                            url = this.select_data(con, request, response);
                        } else if (str_op.equals("INSERT")) {
                            url = this.insert_data(con, request, response);
                        } else if (str_op.equals("DELETE")) {
                            url = this.delete_data(con, request, response);
                        }
                    } else {
                        url = "sinpermiso.jsp";
                    }
                } else {
                    url = "admin.jsp";
                }
            }
            mostrar_pagina(url, request, response);
        } catch (Exception e) {
            e.printStackTrace(out);
        }
    }

    public void mostrar_pagina(String url, HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        RequestDispatcher disp = req.getRequestDispatcher(url);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setCharacterEncoding("windows-1252");
        resp.setHeader("Pragma", "no-cache");
        resp.setIntHeader("Expires", 0);
        disp.forward(req, resp);
    }

    public DBConfig getDataBaseConfig() {
        ServletContext scon = getServletContext();
        DBConfig dc = new DBConfig();
        dc.setDbname(scon.getInitParameter("dbname"));
        dc.setServer(scon.getInitParameter("dbserver"));
        dc.setUser(scon.getInitParameter("dbuser"));
        dc.setPass(scon.getInitParameter("dbpass"));
        return dc;
    }

    //<editor-fold defaultstate="collapsed" desc="Métodos ABM (SELECT, INSERT, UPDATE y DELETE).">
    public String select_data(Connection con, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "permisoxmodulo.jsp?modo=ASIGNA";
        String idmodulo = (String) request.getParameter("idmodulo");

        String sql = "";
        Statement stm = null;

        con.setAutoCommit(false);

        if (idmodulo != null) {
            sql = "select idpermiso, descripcion as permiso, "+ idmodulo + " as idmodulo " +
                    " from permiso " +
                    " where idpermiso not in " +
                    " (select idpermiso from modulo_permiso where idmodulo = "+ idmodulo +")";

            stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            System.out.println(sql);
            ResultSet result = stm.executeQuery(sql);

            IteradorModuloPermiso ur = new IteradorModuloPermiso(result);
            
            if (ur.getCantidad() == 0) {
                sql = "select idpermiso, descripcion as permiso, "+ idmodulo + " as idmodulo " +
                    " from permiso; ";
                    
                stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);

                System.out.println(sql);
                result = stm.executeQuery(sql);

                ur = new IteradorModuloPermiso(result);
            }
            
            request.setAttribute("PermisosFaltantes", ur);

            sql = " select mp.idmodulo, m.descripcion as modulo, mp.idpermiso, " +
                    " p.descripcion as permiso" +
                    " from modulo_permiso mp" +
                    "   join modulo m on mp.idmodulo = m.idmodulo " +
                    "   join permiso p on mp.idpermiso = p.idpermiso" +
                    " where mp.idmodulo = " + idmodulo +
                    " order by m.descripcion, p.descripcion;";

            stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            System.out.println(sql);
            ResultSet result2 = stm.executeQuery(sql);

            IteradorModuloPermiso rmp = new IteradorModuloPermiso(result2);

            request.setAttribute("PermisosModulo", rmp);
        }

        Modulo modulo = new Modulo();
        modulo.setCon(con);
        modulo.getModulos();

        IteradorModulo itm = (IteradorModulo) modulo.getIteratorAll();
        request.setAttribute("Modulos", itm);

        return url;
    }

    public String insert_data(Connection con, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "";
        String idmodulo = request.getParameter("idmodulo");
        String idpermiso = request.getParameter("idpermiso");

        String sql = "";
        Statement stm = null;

        con.setAutoCommit(false);

        if (idpermiso != null && idmodulo != null) {
            sql = "INSERT INTO modulo_permiso SELECT " + idmodulo + "," + idpermiso + ";";

            stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            System.out.println(sql);
            int cant = stm.executeUpdate(sql);
            System.out.println("Fila ingresada: " + cant);
            con.commit();

            url = select_data(con, request, response);
        }
        return url;
    }

    public String delete_data(Connection con, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "";
        String idmodulo = request.getParameter("idmodulo");
        String idpermiso = request.getParameter("idpermiso");

        String sql = "";
        Statement stm = null;

        con.setAutoCommit(false);

        if (idpermiso != null && idmodulo != null) {
            sql = "DELETE FROM modulo_permiso where idmodulo = " + idmodulo + " and idpermiso = " + idpermiso + ";";

            stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            System.out.println(sql);
            int cant = stm.executeUpdate(sql);
            System.out.println("Fila borrada: " + cant);
            con.commit();

            url = select_data(con, request, response);
        }
        return url;
    }
    //</editor-fold>
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    public void destroy() {
    }

    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    @Override
    public String getServletInfo() {
        return "Este servlet maneja las peticiones sobre la tabla Permiso";
    }
// </editor-fold>
}
